package service

import (
	"context"
	"database/sql"
	"fx_swift_ifcgate_agent/api"
	"fx_swift_ifcgate_agent/internal/model"
	"fx_swift_ifcgate_agent/pkg/code"
	"fx_swift_ifcgate_agent/pkg/global"
	"fx_swift_ifcgate_agent/pkg/internalerrors"
	"fx_swift_ifcgate_agent/pkg/logger"
	"fx_swift_ifcgate_agent/pkg/page"
	"fx_swift_ifcgate_agent/pkg/utils"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/jinzhu/copier"
	"github.com/spf13/cast"
	"sync"
	"time"
)

type IAgentSrv interface {
	// 查询企业帐户申请
	QueryAgentApply(ctx context.Context) (*api.EnterpriseAccountApplyRes, error)

	// 填写企业帐户资料
	UploadEnterpriseInfo(ctx context.Context, req *api.EnterpriseAccountApplyReq) error

	//开户趋势
	MerOpenTrend(ctx context.Context) (*api.MerOpenTrendRes, error)

	//按时间查询开户趋势
	MerOpenTrendDynamic(ctx context.Context, req *api.MerOpenTrendReq) ([]*api.DynamicDateRes, error)

	//账户状态
	GetMerStatusBoss(ctx context.Context) ([]*api.MerOpenStatusRes, error)

	//企业审核列表
	GetAllMerChantAuditList(ctx context.Context, req *api.MerChantBossReq) (*page.Collection[*api.MerChantBossRes], error)

	//企业列表
	GetAllMerChantSuccList(ctx context.Context, req *api.MerChantBossReq) (*page.Collection[*api.MerChantBossSuccRes], error)

	//企业详情
	GetMerChantTemp(ctx context.Context, acct string) (*api.MerChantTempRes, error)

	//获取待审核企业数
	GetAuditNums(ctx context.Context) (int, error)

	//获取业务性质
	QueryBusinessNature(ctx context.Context, natureType string) ([]*api.BusinessNatureRes, error)

	//获取资金来源
	QuerySourceFund(ctx context.Context) ([]*api.SourceFundRes, error)

	//获取付款目的
	QueryPaymentPurpose(ctx context.Context) ([]*api.PaymentPurposeRes, error)

	// 企业类型
	GetCompanyType(ctx context.Context) ([]*api.GetCompanyTypeRes, error)
}

type agentSrv struct {
}

func NewAgentSrv() IAgentSrv {
	return &agentSrv{}
}

// 企业类型
func (a *agentSrv) GetCompanyType(ctx context.Context) ([]*api.GetCompanyTypeRes, error) {
	var (
		err             error
		companyTypeList []*model.IfcgateCompanyType
		result          = make([]*api.GetCompanyTypeRes, 0)
	)
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_company_type").Where("1=1").Scan(&companyTypeList); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	for _, value := range companyTypeList {
		result = append(result, &api.GetCompanyTypeRes{
			Id: value.ID,
			NameInfo: api.NameInfo{
				ChineseName: value.ChineseName,
				EnglishName: value.EnglishName,
			},
		})
	}
	return result, err
}

// 企业列表
func (m agentSrv) GetAllMerChantSuccList(ctx context.Context, req *api.MerChantBossReq) (*page.Collection[*api.MerChantBossSuccRes], error) {
	var (
		err        error
		resultList []*api.MerChantBossSuccRes
		total      int
	)

	collectionDto := &page.Collection[*api.MerChantBossSuccRes]{}
	collectionDto.Page = req.PageNo
	collectionDto.PageSize = req.PageSize

	agentAccount := ctx.Value("Account").(string)
	db := global.GFDB.Ctx(ctx).Schema("fx")
	mod := db.Model("ifcgate_merchant_va_info imvi").
		LeftJoin("ifcgate_company_user icu", "imvi.account=icu.account").
		LeftJoin("select a.account,a.status from (select status,account,created_at from fx.ifcgate_fee where fee_type='00') a left join (select max(created_at) as created_at,max(account) as account from ifcgate_fee where fee_type='00' group by account) b on a.account=b.account and a.created_at=b.created_at where b.account is not null", "imvi.account=fee.account").As("fee")
	mod.Where("icu.account!='' and icu.agent_account=?", agentAccount)
	if len(req.MerName) > 0 {
		mod.WhereOrLike("imvi.mer_name_en", "%"+req.MerName+"%")
		mod.WhereOrLike("imvi.mer_name_cn", "%"+req.MerName+"%")
	}
	if len(req.PhoneNum) > 0 {
		mod.Where("imvi.phone_num like ?", "%"+req.PhoneNum+"%")
	}
	if len(req.StartTime) > 0 {
		mod.Where("imvi.created_at>=?", req.StartTime+" 00:00:00")
	}
	if len(req.EndTime) > 0 {
		mod.Where("imvi.created_at<=?", req.EndTime+" 23:59:59")
	}
	mod.Where("imvi.status=?", "SUCC")
	mod.Fields("imvi.mer_order_no,imvi.merchant_no,imvi.email,imvi.country_code,imvi.phone_num,imvi.mer_name_en,imvi.mer_name_cn," +
		"imvi.created_at,imvi.updated_at,imvi.status,imvi.account,if(fee.status is null,'',fee.status) as fee_status")
	if len(req.SortFields) > 0 && len(req.SortMethod) > 0 {
		mod.Order(req.SortFields + " " + req.SortMethod)
	}
	mod.Order("imvi.created_at desc")
	mod.Limit(int(page.PageToOffset(req.PageNo, req.PageSize)), cast.ToInt(req.PageSize))
	err = mod.ScanAndCount(&resultList, &total, false)
	collectionDto.TotalPage = page.GetTotalPage(req.PageNo, req.PageSize, cast.ToInt64(total))

	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}

	//循环获取企业va开户成功数
	type BankNum struct {
		Num        int    `json:"num"`
		MerChantNo string `json:"merchant_no"`
	}
	bankNumObj := []BankNum{}
	if err = db.Model("ifcgate_va_info").
		Where("status='ON'").
		Group("merchant_no").
		Fields("count(1) as num,merchant_no").Scan(&bankNumObj); err != nil {
		logger.SugarLogger.Error(err)
	}

	if resultList != nil {
		for _, value := range resultList {
			value.BankNums = 0
			if bankNumObj != nil {
				for _, numValue := range bankNumObj {
					if value.MerChantNo == numValue.MerChantNo && numValue.Num >= 0 {
						value.BankNums = numValue.Num
					}
				}
			}
		}
	}
	collectionDto.Total = cast.ToInt64(total)
	collectionDto.List = resultList

	return collectionDto, err
}

// 获取付款目的
func (m agentSrv) QueryPaymentPurpose(ctx context.Context) ([]*api.PaymentPurposeRes, error) {
	var (
		err        error
		paymentObj []*model.IFCGatePaymentPurpose
	)
	if err = global.GFDB.Ctx(ctx).Schema("fx").Model("ifcgate_payment_purpose_base").Scan(&paymentObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}

	if paymentObj == nil {
		return []*api.PaymentPurposeRes{}, nil
	}

	result := make([]*api.PaymentPurposeRes, 0)
	for _, value := range paymentObj {
		result = append(result, &api.PaymentPurposeRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

// 获取资金来源
func (m agentSrv) QuerySourceFund(ctx context.Context) ([]*api.SourceFundRes, error) {
	var (
		err           error
		sourceFundObj []*model.IFCGateSourceFund
	)
	if err = global.GFDB.Ctx(ctx).Schema("fx").Model("ifcgate_source_funds_base").Scan(&sourceFundObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询数据报错")
	}
	if sourceFundObj == nil {
		return []*api.SourceFundRes{}, nil
	}

	result := make([]*api.SourceFundRes, 0)
	for _, value := range sourceFundObj {
		result = append(result, &api.SourceFundRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

// 获取业务性质
func (m agentSrv) QueryBusinessNature(ctx context.Context, natureType string) ([]*api.BusinessNatureRes, error) {
	var (
		err       error
		natureObj []*model.IFCGateNature
	)
	if natureType == "" {
		return nil, internalerrors.New(code.ErrUnknown, "业务性质类型不能为空")
	}

	if err = global.GFDB.Ctx(ctx).Schema("fx").Model("ifcgate_nature_base").Where("nature_type", natureType).Scan(&natureObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询数据报错")
	}
	if natureObj == nil {
		return []*api.BusinessNatureRes{}, nil
	}

	result := make([]*api.BusinessNatureRes, 0)
	for _, value := range natureObj {
		result = append(result, &api.BusinessNatureRes{
			Code: value.Code,
			Desc: value.Desc,
		})
	}
	return result, err
}

func (m agentSrv) GetAuditNums(ctx context.Context) (int, error) {
	var (
		err  error
		nums int
	)
	nums = 0
	agentAccount := ctx.Value("Account").(string)
	count, err := global.GFDB.Schema("fx").Model("ifcgate_merchant_va_info imvi").
		LeftJoin("ifcgate_company_user icu", "imvi.account=icu.account").
		Where("icu.account!='' and icu.agent_account=? and imvi.status!=?", agentAccount, "SUCC").Count()
	if err != nil {
		logger.SugarLogger.Error(err)
	}
	if count >= 0 {
		nums = count
	}
	return nums, err
}

func (m agentSrv) GetMerChantTemp(ctx context.Context, acct string) (*api.MerChantTempRes, error) {
	var (
		err        error
		reqJsonObj *model.IFCGATEMerChantVATmp
	)

	if err = global.GFDB.Ctx(ctx).Schema("fx").Model("ifcgate_merchant_va_tmp").Where("account=?", acct).
		Scan(&reqJsonObj); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	if reqJsonObj == nil {
		return &api.MerChantTempRes{}, nil
	}

	return &api.MerChantTempRes{
		Account: reqJsonObj.Account,
		ReqJson: reqJsonObj.ReqJson,
	}, nil
}

func (m agentSrv) GetAllMerChantAuditList(ctx context.Context, req *api.MerChantBossReq) (*page.Collection[*api.MerChantBossRes], error) {
	var (
		err        error
		resultList []*api.MerChantBossRes
		total      int
	)

	collectionDto := &page.Collection[*api.MerChantBossRes]{}
	collectionDto.Page = req.PageNo
	collectionDto.PageSize = req.PageSize

	agentAccount := ctx.Value("Account").(string)
	mod := global.GFDB.Ctx(ctx).Schema("fx").Model("ifcgate_merchant_va_info imvi").
		LeftJoin("ifcgate_company_user icu", "imvi.account=icu.account")
	mod.Where("icu.account!=''")
	mod.Where("icu.agent_account=?", agentAccount)
	if len(req.MerName) > 0 {
		mod.Where("imvi.mer_name_en like ? or imvi.mer_name_cn like ?", "%"+req.MerName+"%", "%"+req.MerName+"%")
		//mod.WhereOrLike("mer_name_cn", "%"+req.MerName+"%")
	}
	if len(req.PhoneNum) > 0 {
		mod.Where("imvi.phone_num like ?", "%"+req.PhoneNum+"%")
	}
	if len(req.Status) > 0 {
		mod.Where("imvi.status=?", req.Status)
	}
	if len(req.StartTime) > 0 {
		mod.Where("imvi.created_at>=?", req.StartTime+" 00:00:00")
	}
	if len(req.EndTime) > 0 {
		mod.Where("imvi.created_at<=?", req.EndTime+" 23:59:59")
	}
	mod.Where("imvi.status!=?", "SUCC")
	if len(req.SortFields) > 0 && len(req.SortMethod) > 0 {
		mod.Order(req.SortFields + " " + req.SortMethod)
	}
	mod.Fields("imvi.mer_order_no,imvi.email,imvi.country_code,imvi.phone_num,imvi.mer_name_en,imvi.mer_name_cn," +
		"imvi.created_at,imvi.updated_at,imvi.status,imvi.message,imvi.account")
	mod.Order("imvi.created_at desc")
	mod.Limit(int(page.PageToOffset(req.PageNo, req.PageSize)), cast.ToInt(req.PageSize))
	err = mod.ScanAndCount(&resultList, &total, false)
	collectionDto.TotalPage = page.GetTotalPage(req.PageNo, req.PageSize, cast.ToInt64(total))

	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}

	collectionDto.Total = cast.ToInt64(total)
	collectionDto.List = resultList

	return collectionDto, err
}

// 获取代理端端账户状态
func (m agentSrv) GetMerStatusBoss(ctx context.Context) ([]*api.MerOpenStatusRes, error) {
	var (
		err          error
		merStatusObj []*api.MerOpenStatusRes
	)
	agentAccount := ctx.Value("Account").(string)
	mod := global.GFDB.Schema("fx").Model("ifcgate_merchant_va_info imvi").
		LeftJoin("ifcgate_company_user icu", "imvi.account=icu.account")
	mod.Where("icu.account!=''")
	mod.Where("icu.agent_account=?", agentAccount)
	mod.Where("imvi.status!=", "ACCEPT")
	mod.Where("imvi.status!=", "PENDING")
	mod.Where("imvi.status!=", "APPROVAL")
	mod.Fields("imvi.status,count(1) as num").Group("imvi.status")
	err = mod.Scan(&merStatusObj)
	if err != nil {
		logger.SugarLogger.Error(err)
		return []*api.MerOpenStatusRes{}, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	if merStatusObj == nil {
		logger.SugarLogger.Error(err)
		return []*api.MerOpenStatusRes{}, nil
	}

	acceptNums := 0
	count, err := global.GFDB.Schema("fx").Model("ifcgate_merchant_va_info imvi").
		LeftJoin("ifcgate_company_user icu", "imvi.account=icu.account").
		FieldCount("imvi.status").
		Where("icu.account!='' and icu.agent_account=? and (imvi.status =? or imvi.status =? or imvi.status=?)", agentAccount, "ACCEPT", "PENDING", "APPROVAL").
		Sum("imvi.status")
	if err != nil {
		logger.SugarLogger.Error(err)
	}
	if count >= 0 {
		acceptNums = int(count)
	}

	for _, value := range merStatusObj {
		if value.Status == "REFUSE" {
			value.Status = "PROCESSING"
			value.Num = value.Num + acceptNums
		}
	}

	return merStatusObj, nil
}

// 获取开户趋势-按时间范围查询
func (a agentSrv) MerOpenTrendDynamic(ctx context.Context, req *api.MerOpenTrendReq) ([]*api.DynamicDateRes, error) {
	var (
		err            error
		sqlStr         string
		dynamicDateObj []*api.DynamicDateRes
	)

	flag := 0
	agentAccount := ctx.Value("Account").(string)
	if req.StartTime == "" || req.EndTime == "" {
		return []*api.DynamicDateRes{}, internalerrors.New(code.ErrUnknown, "请选择具体时间范围")
	}

	startT, err := time.Parse("2006-01-02 15:04:05", req.StartTime)
	if err != nil {
		logger.SugarLogger.Error("startT时间解析错误")
	}
	endT, err := time.Parse("2006-01-02 15:04:05", req.EndTime)
	if err != nil {
		logger.SugarLogger.Error("endT时间解析错误")
	}
	diff := endT.Sub(startT)
	startYear, startMonth, _ := startT.Date()
	endYear, endMonth, _ := endT.Date()
	//如果两个日期天数大于30，并且月份不同
	if diff.Hours()/24 >= 30 {
		//按月获取趋势数据
		if startYear != endYear || startMonth != endMonth {
			flag = 1
			sqlStr = "select DATE_FORMAT(created_at,'%Y-%m') as `date`,count(1) as num from (select account,created_at,`status` from fx.ifcgate_merchant_va_info) a left join (select account from fx.ifcgate_company_user where agent_account=?) b on a.account=b.account where b.account!='' and a.status='SUCC' and a.created_at >=? and a.created_at <=? group by DATE_FORMAT(a.created_at,'%Y-%m')"
		} else {
			sqlStr = "select DATE_FORMAT(created_at,'%Y-%m-%d') as `date`,count(1) as num from (select account,created_at,`status` from fx.ifcgate_merchant_va_info) a left join (select account from fx.ifcgate_company_user where agent_account=?) b on a.account=b.account where b.account!='' and a.status='SUCC' and a.created_at >=? and a.created_at <=? group by DATE_FORMAT(a.created_at,'%Y-%m-%d')"
		}
	} else {
		sqlStr = "select DATE_FORMAT(created_at,'%Y-%m-%d') as `date`,count(1) as num from (select account,created_at,`status` from fx.ifcgate_merchant_va_info) a left join (select account from fx.ifcgate_company_user where agent_account=?) b on a.account=b.account where b.account!='' and a.status='SUCC' and a.created_at >=? and a.created_at <=? group by DATE_FORMAT(a.created_at,'%Y-%m-%d')"
	}

	err = global.GFDB.Raw(sqlStr, agentAccount, req.StartTime, req.EndTime).Scan(&dynamicDateObj)
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	var dayList []string
	var dynamicObj []*api.DynamicDateRes
	if flag == 0 {
		dayList = utils.GenerateDayList(startT, endT)
	} else {
		dayList = utils.GenerateMonthList(startT, endT)
	}
	for _, day := range dayList {
		dynamicVO := &api.DynamicDateRes{}
		dynamicVO.Date = day
		dynamicVO.Num = 0
		for _, value := range dynamicDateObj {
			if value.Date == day {
				dynamicVO.Num = value.Num
			}
		}
		dynamicObj = append(dynamicObj, dynamicVO)
	}

	return dynamicObj, err
}

// 获取代理端端开户趋势
func (a agentSrv) MerOpenTrend(ctx context.Context) (*api.MerOpenTrendRes, error) {
	var (
		err error
		//merOpenTrendObj *api.MerOpenTrendRes
	)
	type Last7Days struct {
		Date string `json:"date"`
		Num  int    `json:"num"`
	}

	type Last2Weeks struct {
		Date string `json:"date"`
		Num  int    `json:"num"`
	}

	type ThisYears struct {
		Date string `json:"date"`
		Num  int    `json:"num"`
	}

	type LastMonths struct {
		Date string `json:"date"`
		Num  int    `json:"num"`
	}
	//获取代理商account
	agentAccount := ctx.Value("Account").(string)

	last7Days := []Last7Days{}
	last2Weeks := []Last2Weeks{}
	lastMonths := []LastMonths{}
	lastYears := []ThisYears{}

	db := global.GFDB.Ctx(ctx)
	err = db.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		sqlStr := "select DATE_FORMAT(a.created_at,'%Y-%m-%d') as `date`,count(1) as num from (select account,created_at,`status` from fx.ifcgate_merchant_va_info) a left join (select account from fx.ifcgate_company_user where agent_account=?) b on a.account=b.account where b.account!='' and a.status='SUCC' and created_at >=DATE_SUB(CURDATE(),INTERVAL 7 DAY) group by DATE_FORMAT(a.created_at,'%Y-%m-%d')"
		err = global.GFDB.Raw(sqlStr, agentAccount).Scan(&last7Days)
		if err != nil {
			return internalerrors.New(code.ErrUnknown, "数据查询异常")
		}

		sqlStr = "select DATE_FORMAT(a.created_at,'%Y-%m-%d') as `date`,count(1) as num from (select account,created_at,`status` from fx.ifcgate_merchant_va_info) a left join (select account from fx.ifcgate_company_user where agent_account=?) b on a.account=b.account where b.account!='' and a.status='SUCC' and created_at >=DATE_SUB(CURDATE(),INTERVAL 14 DAY) group by DATE_FORMAT(a.created_at,'%Y-%m-%d')"
		err = global.GFDB.Raw(sqlStr, agentAccount).Scan(&last2Weeks)
		if err != nil {
			return internalerrors.New(code.ErrUnknown, "数据查询异常")
		}

		lastMonths := []LastMonths{}
		sqlStr = "select DATE_FORMAT(a.created_at,'%Y-%m-%d') as `date`,count(1) as num from (select account,created_at,`status` from fx.ifcgate_merchant_va_info) a left join (select account from fx.ifcgate_company_user where agent_account=?) b on a.account=b.account where b.account!='' and a.status='SUCC' and created_at >=DATE_SUB(CURDATE(),INTERVAL 30 DAY) group by DATE_FORMAT(a.created_at,'%Y-%m-%d')"
		err = global.GFDB.Raw(sqlStr, agentAccount).Scan(&lastMonths)
		if err != nil {
			return internalerrors.New(code.ErrUnknown, "数据查询异常")
		}

		lastYears := []ThisYears{}
		sqlStr = "select DATE_FORMAT(a.created_at,'%Y-%m') as `date`,count(1) as num from (select account,created_at,`status` from fx.ifcgate_merchant_va_info) a left join (select account from fx.ifcgate_company_user where agent_account=?) b on a.account=b.account where b.account!='' and a.status='SUCC' and created_at >=DATE_SUB(CURDATE(),INTERVAL 1 YEAR) group by DATE_FORMAT(a.created_at,'%Y-%m')"
		err = global.GFDB.Raw(sqlStr, agentAccount).Scan(&lastYears)
		if err != nil {
			return internalerrors.New(code.ErrUnknown, "数据查询异常")
		}

		return err
	})

	var wg sync.WaitGroup
	//获取近7天趋势
	last7DayObj := []Last7Days{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		if last7Days != nil {
			timeNow := time.Now().Format("2006-01-02")
			endTime, _ := time.Parse("2006-01-02", timeNow)
			startTime := endTime.AddDate(0, 0, -6)
			dayList := utils.GenerateDayList(startTime, endTime)
			for _, day := range dayList {
				last7DayVO := Last7Days{}
				last7DayVO.Date = day
				last7DayVO.Num = 0
				for _, value := range last7Days {
					if value.Date == day {
						last7DayVO.Num = value.Num
					}
				}
				last7DayObj = append(last7DayObj, last7DayVO)
			}
		}
	}()

	//获取近2周趋势
	last2WeekObj := []Last2Weeks{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		if last2Weeks != nil {
			timeNow := time.Now().Format("2006-01-02")
			endTime, _ := time.Parse("2006-01-02", timeNow)
			startTime := endTime.AddDate(0, 0, -13)
			dayList := utils.GenerateDayList(startTime, endTime)
			for _, day := range dayList {
				last2WeekVO := Last2Weeks{}
				last2WeekVO.Date = day
				last2WeekVO.Num = 0
				for _, value := range last2Weeks {
					if value.Date == day {
						last2WeekVO.Num = value.Num
					}
				}
				last2WeekObj = append(last2WeekObj, last2WeekVO)
			}
		}
	}()

	//获取近30天趋势
	lastMonthObj := []LastMonths{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		if lastMonths != nil {
			timeNow := time.Now().Format("2006-01-02")
			endTime, _ := time.Parse("2006-01-02", timeNow)
			startTime := endTime.AddDate(0, 0, -29)
			dayList := utils.GenerateDayList(startTime, endTime)
			for _, day := range dayList {
				lastMonthVO := LastMonths{}
				lastMonthVO.Date = day
				lastMonthVO.Num = 0
				for _, value := range lastMonths {
					if value.Date == day {
						lastMonthVO.Num = value.Num
					}
				}
				lastMonthObj = append(lastMonthObj, lastMonthVO)
			}
		}
	}()

	//获取近一年趋势
	lastYearObj := []ThisYears{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		if lastYears != nil {
			timeNow := time.Now().Format("2006-01-02")
			endTime, _ := time.Parse("2006-01-02", timeNow)
			startTime := endTime.AddDate(-1, 0, 0)
			dayList := utils.GenerateMonthList(startTime, endTime)
			for _, day := range dayList {
				lastYearVO := ThisYears{}
				lastYearVO.Date = day
				lastYearVO.Num = 0
				for _, value := range lastYears {
					if value.Date == day {
						lastYearVO.Num = value.Num
					}
				}
				lastYearObj = append(lastYearObj, lastYearVO)
			}
			lastYearObj = lastYearObj[1:]
		}
	}()
	//等待所有并发完成
	wg.Wait()

	//组装返回结果集
	type MerOpenTrendRes struct {
		Last7DaysList  []Last7Days  `json:"last7DayList"`
		Last2WeeksList []Last2Weeks `json:"last2WeeksList"`
		LastMonthsList []LastMonths `json:"lastMonthsList"`
		ThisYearsList  []ThisYears  `json:"thisYearsList"`
	}
	dbVO := MerOpenTrendRes{
		Last7DaysList:  last7DayObj,
		Last2WeeksList: last2WeekObj,
		LastMonthsList: lastMonthObj,
		ThisYearsList:  lastYearObj,
	}
	merOpenTrendRes := &api.MerOpenTrendRes{}
	copier.Copy(&merOpenTrendRes, &dbVO)

	return merOpenTrendRes, nil
}

// 查询企业帐户申请
func (a *agentSrv) QueryAgentApply(ctx context.Context) (*api.EnterpriseAccountApplyRes, error) {
	var (
		err      error
		applyObj *model.IfcgateEnterpriseAccountApply
		account  string
	)
	account = ctx.Value("Account").(string)
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_enterprise_account_apply").Where("account", account).Scan(&applyObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询报错")
	}
	if applyObj == nil {
		return nil, internalerrors.New(code.ErrUnknown, "该帐户存在异常")
	}

	return &api.EnterpriseAccountApplyRes{
		CountryCode:    applyObj.CountryCode,
		Additional:     applyObj.Image,
		CompanyName:    applyObj.CompanyName,
		RegisterCode:   applyObj.RegisterCode,
		CompanyTime:    applyObj.CompanyTime,
		CompanyAddress: applyObj.CompanyAddress,
		CompanyType:    cast.ToInt64(applyObj.CompanyType),
		ContactPerson:  applyObj.ContactPerson,
		Phone:          applyObj.Phone,
		Status:         applyObj.Status,
		RefuseReason:   applyObj.RefuseReason,
	}, nil
}

// 填写企业帐户资料
func (a *agentSrv) UploadEnterpriseInfo(ctx context.Context, req *api.EnterpriseAccountApplyReq) error {
	g.Dump(req)
	var (
		err      error
		result   sql.Result
		applyObj *model.IfcgateEnterpriseAccountApply
		nums     int64
		account  string
	)
	account = ctx.Value("Account").(string)
	if req.Status == "draft" {
		result, err = global.GFDB.Model("ifcgate_enterprise_account_apply").Data(
			g.Map{"country_code": req.CountryCode, "company_name": req.CompanyName, "register_code": req.RegisterCode, "company_time": req.CompanyTime,
				"company_type": req.CompanyType, "company_address": req.CompanyAddress, "contact_person": req.ContactPerson,
				"phone": req.Phone, "image": req.Additional}).
			Where("account=?", account).Update()
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
		nums, err = result.RowsAffected()
		if nums == 0 || err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
	} else if req.Status == "init" {
		if err = global.GFDB.Ctx(ctx).Model("ifcgate_enterprise_account_apply").
			Where("account", account).Scan(&applyObj); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "查询报错")
		}
		if applyObj == nil {
			return internalerrors.New(code.ErrUnknown, "该帐户存在异常")
		}
		result, err = global.GFDB.Model("ifcgate_enterprise_account_apply").Data(
			g.Map{"country_code": req.CountryCode, "company_name": req.CompanyName, "register_code": req.RegisterCode, "company_time": req.CompanyTime,
				"company_type": req.CompanyType, "company_address": req.CompanyAddress, "contact_person": req.ContactPerson,
				"phone": req.Phone, "image": req.Additional, "status": req.Status}).
			Where("account=?", account).Update()
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
		nums, err = result.RowsAffected()
		if nums == 0 || err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
	}

	return err
}
